
const { User } = require('../db/model/index.js');
const { formatUser } = require('./_format.js')

async function getUserInfo(userName,password) {
  let whereOpt = {userName};
  if (password) {
    whereOpt = Object.assign(whereOpt,{password})
  }
  const result = await User.findOne({
    attributes: ['id','userName','nickName','picture','city'],
    where: whereOpt
  });
  
  if (!result) {    // 没有查询到书库时，result === null
    return null
  } else {
    return  formatUser(result.dataValues)
  }

}

async function createUser({userName, password, gender, nickName }) {
  const result = await User.create({
    userName,
    password, 
    gender,
    nickName: nickName ? nickName : userName
  });
  // console.log('register-result:',result);
  if (result && result.dataValues) {
    return result.dataValues;
  } else {
    return null
  }
}

async function deleteUser(userName) {
  const result = await User.destroy({
    where: {
      userName
    }
  })
  return result > 0
}

module.exports = {
  getUserInfo,
  createUser,
  deleteUser
}